<?php

namespace app\admin\controller;

use think\Db;
use \app\common\model\Shop as ShopModel;
use think\Validate;

/**
 * 后台用户控制器
 */
class Shop extends Home

{
    /**
     * 商品分类
     * @return mixed
     */
    public function shopcategory()
    {
        $cates = Db('shop_category')->where('status', 1)->select();
//        $cates = [];
//        /*方法一(用于前台显示)*/
//        /*必须是键名和id号一致*/
//
//        foreach ($items as $v) {
//            $cates[$v['id']] = $v;
//        }
//        $tree = array();
//        foreach ($cates as $item) {
//            if (isset($cates[$item['pid']])) {
//                $cates[$item['pid']]['son'][] = &$cates[$item['id']];
//            } else {
//                $tree[] = &$cates[$item['id']];
//            }
//        }

        /*方法二*/
        $tree = $this->shopcates($cates);
        $this->assign('_list', $tree);
        $this->assign('title', '商品分类');
        return $this->fetch();
    }

    /**
     * 无限极分类(最重要)
     * @param $cates
     * @param int $pid
     * @param int $level
     * @return array
     */
    public function shopcates($cates, $pid = 0, $level = 0)
    {
        $arr = [];
        foreach ($cates as &$v) {
            if ($v['pid'] == $pid) {
                $v['title'] = sprintf('%s%s', str_repeat('--', $level), $v['title']);
//                if ($v['level'] == 1) {
//                    $v['_disabled'] = 'disabled';
//                } else {
//                    $v['_disabled'] = '';
//                }

                $v['_disabled'] = '';
                $arr[] = $v;
                $arr = array_merge($arr, $this->shopcates($cates, $v['id'], $level + 1));
            }
        }
        return $arr;
    }

    /**
     * 编辑或新增栏目
     * @return mixed
     */
    public function editCate()
    {
        $id = input('id');
        if (request()->isPost()) {
            $data = request()->post();
            if (empty($data['title'])) {
                $this->error('栏目名称不能为空！');
            }
            $pid = $data['pid'];
            if ($pid == 0) {
                $level = 1;
                if (!trim($data['mark'])) {
                    $this->error('请务必输入分类标记！');
                }
                $mark = trim($data['mark']);
            } else {
                $pinfo = Db('shop_category')->field('level,mark')->where('id', $pid)->find();
                $level = $pinfo['level'] + 1;
                $mark = $pinfo['mark'];
            }

            if ($level > 2) {
                $this->error('分类最多不可超过2级！');
            }

            $data['level'] = $level;
            $data['mark'] = $mark;

            if ($id) {
                $res = Db('shop_category')->update($data);
            } else {
//                $cate = Db('shop_category')->where('title', $data['title'])->find();
//                if ($cate) {
//                    $this->error('该栏目已存在！');
//                }
                $data['create_time'] = time();
                $data['status'] = 1;
                $res = Db('shop_category')->insert($data);
            }
            if ($res) {
                $this->success('操作成功！', url('shopcategory'));
            } else {
                $this->error('操作失败！');
            }
        } else {
            $cates = Db('shop_category')->where('status', 1)->select();
            $shopCates = $this->shopcates($cates);
            $shopCate = Db('shop_category')->where('id', $id)->find();
            $this->assign('shopCate', $shopCate);
            foreach ($shopCates as &$v) {
                $v['_select'] = "";
                $v['_disable'] = "";
                if ($shopCate) {
                    if ($shopCate['pid'] == $v['id']) {
                        $v['_select'] = "selected = 'selected'";
                    }
                    $res = $this->isSon($v['id'], $id);
                    if ($res || $id == $v['id']) {
                        $v['_disable'] = "disabled = 'disabled'";
                    }
                }
            }
            $title = $id ? '编辑分类' : '新增分类';
            $this->assign('shopCates', $shopCates);
            $this->assign('id', $id);
            $this->assign('title', $title);
            return $this->fetch('editcate');
        }
    }

    /**
     * 判断某分类是否是另一分类的子分类
     * @param $sid
     * @param $fid
     * @return bool
     */
    private function isSon($sid, $fid)
    {
        $cates = Db('shop_category')->where('status', 1)->select();
        $sons = $this->shopcates($cates, $fid);
        $data = [];
        foreach ($sons as $v) {
            $data[] = $v['id'];
        }
        if (in_array($sid, $data)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除栏目
     */
    public function delCate()
    {
        if (request()->isPost()) {
            $id = input('id');
            $cate = Db('shop_category')->where('id', $id)->find();
            if (!$cate) {
                $this->error('该栏目不存在！');
            }
            if ($this->hasSon($id)) {
                $this->error('该栏目有子栏目，不能删除！');
            }
            $res = Db('shop_category')->where('id', $id)->delete();
            if ($res) {
                $this->success('删除成功！');
            } else {
                $this->error('删除失败！');
            }
        } else {
            $this->error('非法操作！');
        }
    }


    /**
     * 判断某分类是否有子分类
     * @param $fid
     * @return bool
     */
    private function hasSon($fid)
    {
        $cates = Db('shop_category')->where('status', 1)->select();
        $sons = $this->shopcates($cates, $fid);

        if ($sons) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @return bool
     */
    public function goodslist()
    {
        $list = Db('shop')->paginate(20);
        $page = $list->render();
        $arr = $list->toArray();
        $data = $arr["data"];
//        if ($data) {
//            foreach ($data as &$v) {
//                if ($v['sid'] > 0) {
//                    $v['store_name'] = Db('stores')->where('id', $v['sid'])->value('store_name');
//                }
//            }
//        }

        $this->assign('_list', $data);
        $this->assign('page', $page);
        $this->assign('title', "商品列表");
        return $this->fetch();
    }

    /**
     * 新增商品
     * @return mixed
     */
    public function goodsAdd()
    {
        if (request()->isPost()) {
            $data = $_POST;
            $data['pics'] = trim($data['pics'], ',');
            $shopModel = new ShopModel();
            $shopModel->data($data);
            $shopModel->save();
            if ($shopModel->id) { //注册成功
                $this->success('商品添加成功！', url('goodslist'));
            } else { //注册失败，显示错误信息
                $this->error('商品添加失败！');
            }
        } else {

            $cates = Db('shop_category')->where('status', 1)->select();
            $shopCates = $this->shopcates($cates);

            $this->assign('shopCates', $shopCates);
            $this->assign('title', '新增商品');
            return $this->fetch('goodsadd');
        }
    }

    /**
     * 编辑商品
     * @return mixed
     */
    public function goodsEdit()
    {
        $id = input('id');
        if (request()->isPost()) {
            $data = $_POST;
            $data['pics'] = trim($data['pics'], ',');
            unset($data['id']);
            $res = Db('shop')->where('id', $_POST['id'])->update($data);

            if ($res) {
                $this->success('商品更新成功！', url('goodslist'));
            } else {
                $this->error('商品更新失败！');
            }
        } else {
            $goods = Db('shop')->where('id', $id)->find();

            $pics = explode(',', $goods['pics']);
            $cates = Db('shop_category')->where('status', 1)->select();
            $shopCates = $this->shopcates($cates);

            $this->assign('pics', $pics);
            $this->assign('goodsInfo', $goods);
            $this->assign('shopCates', $shopCates);
            $this->assign('title', '编辑商品');
            return $this->fetch('goodsedit');
        }
    }

    /**
     * 删除商品
     */
    public function delGoods()
    {
        if (request()->isPost()) {
            $id = input('id');
            $cate = Db('shop')->where('id', $id)->find();
            if (!$cate) {
                $this->error('该商品不存在！');
            }
            $res = Db('shop')->where('id', $id)->delete();
            if ($res) {
                $this->success('删除成功！');
            } else {
                $this->error('删除失败！');
            }
        } else {
            $this->error('非法操作！');
        }
    }

    /**
     * 删除图片
     * @param $goodid
     * @param $position
     * @param string $field
     */
    public function changePicc($goodid, $position, $field = 'pics')
    {
        $piccs = Db('shop')->where('id', $goodid)->value($field);
        if (!$piccs) {
            $this->error('无图片可供删除！');
        }
        $position_arr = array_filter(explode(',', $position));
        $piccs_arr = explode(',', trim($piccs, ','));
        foreach ($piccs_arr as $k => $v) {
            $key = $k + 1;
            if (in_array($key, $position_arr)) {
                unset($piccs_arr[$k]);
            }
        }

        $piccs = implode(',', $piccs_arr);
        $res = Db('shop')->where('id', $goodid)->setField($field, $piccs);
        if ($res) {
            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

    public function storeslist()
    {
        $list = Db('stores')->paginate(20);
        $page = $list->render();
        $this->assign('_list', $list);
        $this->assign('page', $page);
        $this->assign('title', "店铺列表");
        return $this->fetch();
    }

    /**
     * 新增商品
     * @return mixed
     */
    public function storeAdd()
    {
        if (request()->isPost()) {
            $data = $_POST;
            $data['status'] = 1;
            $store = Db('stores')->where('store_name', $data['store_name'])->find();
            if ($store) {
                $this->error('该店铺名称已存在！');
            }
            $res = Db('stores')->insert($data);
            if ($res) { //注册成功
                $this->success('店铺添加成功！', url('storeslist'));
            } else { //注册失败，显示错误信息
                $this->error('店铺添加失败！');
            }
        } else {
            $this->assign('title', '新增店铺');
            return $this->fetch('storeadd');
        }
    }

    /**
     * 编辑商品
     * @return mixed
     */
    public function storeEdit()
    {
        $id = input('id');
        if (request()->isPost()) {
            $data = $_POST;
            $store = Db('stores')->where('store_name', $data['store_name'])->where('id', 'neq', $id)->find();
            if ($store) {
                $this->error('该店铺名称已存在！');
            }
            unset($data['id']);
//            $shopModel = new ShopModel();
//            $res = $shopModel->save($data, ['id' => $_POST['id']]);
            $res = Db('stores')->where('id', $id)->update($data);

            if ($res) {
                $this->success('店铺更新成功！', url('storeslist'));
            } else {
                $this->error('店铺更新失败！');
            }
        } else {
            $storeInfo = Db('stores')->where('id', $id)->find();

            $this->assign('storeInfo', $storeInfo);
            $this->assign('title', '编辑店铺');
            return $this->fetch('storeedit');
        }
    }

    /**
     * 删除商品
     */
    public function delStore()
    {
        if (request()->isPost()) {
            $id = input('id');
            $store = Db('stores')->where('id', $id)->find();
            if (!$store) {
                $this->error('该店铺不存在！');
            }
            $res = Db('stores')->where('id', $id)->delete();
            if ($res) {
                $this->success('删除成功！');
            } else {
                $this->error('删除失败！');
            }
        } else {
            $this->error('非法操作！');
        }
    }

    /**
     * 商品活动价格列表
     * @return mixed
     */
    public function priceslist()
    {
        $list = Db('shop_original_price')
            ->alias('p')
            ->join('shop s', 's.id = p.goods_id')
            ->field('p.*,s.goods_name')
            ->order('id desc')
            ->paginate(20);
        $page = $list->render();
        $arr = $list->toArray();
        $data = $arr["data"];
        if ($data) {
            foreach ($data as &$v) {
                $v['begin_time'] = date('Y-m-d H:i:s', $v['begin_time']);
                $v['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
            }
        }

        $this->assign('_list', $data);
        $this->assign('page', $page);
        $this->assign('title', "价格列表");
        return $this->fetch();
    }

    /**
     * 添加活动商品
     * @return mixed
     */
    public function pricesAdd()
    {
        if (request()->isPost()) {
            $data = $_POST;
            $rule = [
                'goods_id' => 'require',
                'original_price' => 'require',
                'begin_date' => 'require',
                'end_date' => 'require',
            ];
            $msg = [
                'goods_id.require' => '商品必选',
                'original_price.require' => '商品成本价必须输入',
                'begin_date.require' => '开始日期必选',
                'end_date.require' => '结束日期必选',
            ];

            $validate = new Validate($rule, $msg);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $data['begin_time'] = strtotime($data['begin_date']);
            $data['end_time'] = strtotime($data['end_date']);

            unset($data['begin_date'], $data['end_date']);
            $res = Db('shop_original_price')->insert($data);
            if ($res) { //注册成功
                $this->success('添加成功！', url('priceslist'));
            } else { //注册失败，显示错误信息
                $this->error('添加失败！');
            }
        } else {
            $goods = Db('shop')->field('id,goods_name')->select();
            $this->assign('goods', $goods);
            $this->assign('title', '新增活动商品');
            return $this->fetch('pricesadd');
        }
    }

    /**
     * 每日报表
     */
    public function dayReport()
    {
        $where = $this->getMap('pay_time');
        $maps = $where['maps'];

        $daysList = [];
        $start = strtotime(date('Y-m-d', strtotime($maps['begintime'])));
        $end = $start + 86400;
        $endz = strtotime(date('Y-m-d', strtotime($maps['endtime']))) + 86400;

        while ($end <= $endz) {
            $items = Db('shoplist')
                ->field('count(num) as nums,goodid')
                ->where('status', '>=', 1)
                ->where('pay_time', '>=', $start)
                ->where('pay_time', '<', $end)
                ->group('goodid')
                ->select();
            if ($items) {
                $nameStr1 = '';
                $nameStr2 = '';
                foreach ($items as $v) {
                    $shopInfo = Db('shop')->field('goods_name,category_id')->where('id', $v['goodid'])->find();
                    $mark = Db('shop_category')->where('id', $shopInfo['category_id'])->value('mark');
                    if ($mark == 'bill') {
                        $nameStr1 .= $shopInfo['goods_name'] . '(<span style="color:red">' . $v['nums'] . '</span>)' . ',';
                    } elseif ($mark == 'cp') {
                        $nameStr2 .= $shopInfo['goods_name'] . '(<span style="color:red">' . $v['nums'] . '</span>)' . ',';
                    }

                }
                $daysList[] = [
                    'id' => date('Y-m-d', $start),
                    'name1' => trim($nameStr1, ','),
                    'name2' => trim($nameStr2, ',')
                ];
            }

            $start += 86400;
            $end = $start + 86400;
        }

        $this->searchCondition($maps);
        $this->assign('_list', array_reverse($daysList));
        $this->assign('search', url('dayReportd'));
        $this->assign('title', '商品报表');
        return $this->fetch('dayreport');
    }

    public function dayReportd()
    {
        $where = $this->getMap('pay_time');
        $maps = $where['maps'];

        $daysList = [];
        $start = strtotime(date('Y-m-d', strtotime($maps['begintime'])));
        $end = $start + 86400;
        $endz = strtotime(date('Y-m-d', strtotime($maps['endtime']))) + 86400;

        while ($end <= $endz) {
            $items = Db('shoplist')
                ->field('count(num) as nums,goodid')
                ->where('status', '>=', 1)
                ->where('pay_time', '>=', $start)
                ->where('pay_time', '<', $end)
                ->group('goodid')
                ->select();
            if ($items) {
                $nameStr1 = '';
                $nameStr2 = '';
                foreach ($items as $v) {
                    $shopInfo = Db('shop')->field('goods_name,category_id')->where('id', $v['goodid'])->find();
                    $mark = Db('shop_category')->where('id', $shopInfo['category_id'])->value('mark');
                    if ($mark == 'bill') {
                        $nameStr1 .= $shopInfo['goods_name'] . '，';
                    } elseif ($mark == 'cp') {
                        $nameStr2 .= $shopInfo['goods_name'] . '，';
                    }

                }
                $daysList[] = [
                    'id' => date('Y-m-d', $start),
                    'name1' => trim($nameStr1, '，'),
                    'name2' => trim($nameStr2, '，')
                ];
            }

            $start += 86400;
            $end = $start + 86400;
        }

        $title = "商品报表";
        $a = array(
            array('id', '时间'),
            array('name1', '报单商品名称及数量'),
            array('name2', '复消商品名称及数量')
        );

        exportExcel($title, $a, $daysList);
    }

    public function teamAchevement()
    {
        $where = $this->getMap('pay_time');
        $map = $where['map'];
        $maps = $where['maps'];
        $usernumber = input('usernumber');
        if (!$usernumber) {
            $member = Db('member')->field('uid,usernumber,realname')->find();
        } else {
            $member = Db('member')->field('uid,usernumber,realname')->where('usernumber', $usernumber)->find();
        }

        $uid = $member['uid'];
        $sids = Db('member')->where('tuijianids', 'like', '%,' . $uid . ',%')->column('uid');
        array_unshift($sids, $uid);

        $items = Db('shoplist')
            ->field('count(num) as nums,goodid')
            ->where('status', '>=', 1)
            ->where('uid', 'in', $sids)
            ->where($map)
            ->group('goodid')
            ->select();

        $nameStr1 = '';
        $nameStr2 = '';
        foreach ($items as $v) {
            $shopInfo = Db('shop')->field('goods_name,category_id')->where('id', $v['goodid'])->find();
            $mark = Db('shop_category')->where('id', $shopInfo['category_id'])->value('mark');
            if ($mark == 'bill') {
                $nameStr1 .= $shopInfo['goods_name'] . '(<span style="color:red">' . $v['nums'] . '</span>)' . ',';
            } elseif ($mark == 'cp') {
                $nameStr2 .= $shopInfo['goods_name'] . '(<span style="color:red">' . $v['nums'] . '</span>)' . ',';
            }
        }

        $this->assign('member', $member);
        $this->assign('nameStr1', trim($nameStr1, ','));
        $this->assign('nameStr2', trim($nameStr2, ','));

        /*追加查询条件*/
        $arr = array(
            array(
                'type' => 'input',
                'name' => 'usernumber',
                'title' => '请输入会员账号等有效信息',
                'value' => $usernumber,
                'inputid' => '',
                'readonly' => '',
            )
        );
        $this->searchCondition($maps, $arr);
        $this->assign('title', '团队业绩');
        return $this->fetch('teamachevement');
    }
}